package com.boxin.ims.modules.wechat.utils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boxin.ims.modules.wechat.entity.ImageMessage;
import com.boxin.ims.modules.wechat.entity.JiuWechatMember;
import com.boxin.ims.modules.wechat.entity.LangType;
import com.boxin.ims.modules.wechat.entity.NewsMessageByMass;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WeChatUserList;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.entity.Witticism;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.weixin.entity.Oauth2Token;

@Service
public class WechatInterfaceUtils  implements ApplicationContextAware{
	
		private static  WeChatService weChatService;
		
		private static WechatDaoHelper daoHelper;
	
		private static final Class String = null;
		private static CloseableHttpClient httpclient = null;
		
		static {
			PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
			// Increase max total connection to 200
			cm.setMaxTotal(200);
			// Increase default max connection per route to 20
			cm.setDefaultMaxPerRoute(20);
			// Increase max connections for localhost:80 to 50
			httpclient = HttpClients.custom()
			        .setConnectionManager(cm)
			        .build();
		}
		
		
		/**
		 * 微信jsapi 获得ticket 后加密算法
		 * 
		 * @author xiaoqian
		 * @param jsapi_ticket
		 * @param url
		 * @return 2015-1-14下午12:17:40
		 */
		public static Map<String, String> sign(String jsapi_ticket, String url) {
			Map<String, String> ret = new HashMap<String, String>();
			// String nonce_str = create_nonce_str();
			// String timestamp = create_timestamp();
			String nonce_str = create_nonce_str();
			String timestamp = System.currentTimeMillis() + "";
			timestamp = StringUtils.right(timestamp, 10);
			String string1;
			String signature = "";

			// 注意这里参数名必须全部小写，且必须有序
			string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str
					+ "&timestamp=" + timestamp + "&url=" + url;
			System.out.println(string1);

			try {
				MessageDigest crypt = MessageDigest.getInstance("SHA-1");
				crypt.reset();
				crypt.update(string1.getBytes("UTF-8"));
				signature = byteToHex(crypt.digest());
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			ret.put("url", url);
			ret.put("jsapi_ticket", jsapi_ticket);
			ret.put("nonceStr", nonce_str);
			ret.put("timestamp", timestamp);
			ret.put("signature", signature);

			return ret;
		}
		
		private static String create_nonce_str() {
			return UUID.randomUUID().toString().replace("-", "");
		}
		
		private static String byteToHex(final byte[] hash) {
			Formatter formatter = new Formatter();
			for (byte b : hash) {
				formatter.format("%02x", b);
			}
			String result = formatter.toString();
			formatter.close();
			return result;
		}
		
		
		/**
		 * @author Jakemanse
		 * @time 2014-12-9  下午5:36:33
		 * @function <p> 获取授权后的 token和openId </p>
		 * @param appid
		 * @param secret
		 * @param oauthCode
		 * {
			   "access_token":"ACCESS_TOKEN",
			   "expires_in":7200,
			   "refresh_token":"REFRESH_TOKEN",
			   "openid":"OPENID",
			   "scope":"SCOPE"
			}
		 * @return
		 */
		public static Oauth2Token getOAuth2Token(String appid,String secret,String oauthCode){
			
			String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+oauthCode+"&grant_type=authorization_code";
			
			try {
				HttpGet get = HttpClientConnectionManager.getGetMethod(url.replace(" ", ""));
				HttpResponse response = httpclient.execute(get);
				String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
				
				
				JSONObject json = (JSONObject) JSON.parse(jsonStr);
				String token = json.getString("access_token");
				String expires_in = json.getString("expires_in");
				String openId =   json.getString("openid");
				String scope  = json.getString("scope");
				String refresh_token = json.getString("refresh_token");
				
				Oauth2Token oauth2Token = new Oauth2Token();
				oauth2Token.setToken(token);
				oauth2Token.setExpires_in(expires_in);
				oauth2Token.setScope(scope);
				oauth2Token.setRefresh_token(refresh_token);
				oauth2Token.setOpenid(openId);
				
				return oauth2Token;
				
				
			} catch (Exception e) {
				
			}
			
			return null;
			
		}
		
		/**
		 * 4、通过网页授权access_token和openid获取用户基本信息（支持UnionID机制）
		 * 
		 * @param accessToken
		 * @param oponId
		 * @param langType
		 * @return
		 * @throws Exception
		 */
		public static JiuWechatMember getUserMessageBysns(String accessToken,
				String oponId, LangType langType) throws Exception {
			String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
					+ accessToken + "&openid=" + oponId + "&lang=" + langType;
			JSONObject object = null;
			HttpGet get = null;
			try {
				get = HttpClientConnectionManager
						.getGetMethod(url.replace(" ", ""));
				HttpResponse response = httpclient.execute(get);
				String jsonStr = EntityUtils
						.toString(response.getEntity(), "utf-8");
				object = JSON.parseObject(jsonStr);
			} catch (Exception e) {
				e.getMessage();
			} finally {
				if (get != null) {
					get.abort();
				}
			}
			JiuWechatMember wechatUser = new JiuWechatMember();
			wechatUser.setCity(object.getString("city"));
			wechatUser.setCountry(object.getString("country"));
			wechatUser.setHeadimgurl(object.getString("headimgurl"));
			wechatUser.setLanguage(object.getString("language"));
			if (object.getString("nickname") != null) {
				wechatUser.setNickname(filterEmoji(object.getString("nickname")));
			}
			wechatUser.setOpenId(object.getString("openid"));
			wechatUser.setProvince(object.getString("province"));
			wechatUser.setSex(object.getString("sex"));
			return wechatUser;
		}
		
		
		
		/**
		 * 获取用户基本信息
		 *@author xiaoqian
		 * @param accessToken
		 * @param oponId
		 * @param langType
		 * @return
		 * @throws Exception
		 * 2014-3-1上午10:53:10
		 */
		public static WechatMember getUserMessage(String accessToken,String oponId,LangType langType)throws Exception{
			String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+oponId+"&lang="+langType;
			HttpGet get = HttpClientConnectionManager.getGetMethod(url.replace(" ", "")); 
			HttpResponse response = httpclient.execute(get);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			
			System.out.println(jsonStr+"============");
			JSONObject object = JSON.parseObject(jsonStr);
			WechatMember wechatUser = new WechatMember();
			wechatUser.setCity(object.getString("city"));
			wechatUser.setCountry(object.getString("country"));
			wechatUser.setHeadimgurl(object.getString("headimgurl"));
			wechatUser.setLanguage(object.getString("language"));
			if(object.getString("nickname")!=null){
				wechatUser.setNickname(filterEmoji(object.getString("nickname")));
			}
			wechatUser.setWechatId(object.getString("openid"));
			wechatUser.setProvince(object.getString("province"));
			wechatUser.setSex(object.getString("sex"));
			//wechatUser.setSubscribe(object.getString("subscribe"));
			return wechatUser;
		}
		
		/**
		 * 获取用户基本信息
		 *@author xiaoqian
		 * @param accessToken
		 * @param oponId
		 * @param langType
		 * @return
		 * @throws Exception
		 * 2014-3-1上午10:53:10
		 */
		public static JiuWechatMember getJiuUserMessage(String accessToken,String oponId,LangType langType)throws Exception{
			String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+oponId+"&lang="+langType;
			HttpGet get = HttpClientConnectionManager.getGetMethod(url.replace(" ", "")); 
			HttpResponse response = httpclient.execute(get);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			
			System.out.println(jsonStr+"============");
			JSONObject object = JSON.parseObject(jsonStr);
			JiuWechatMember wechatUser = new JiuWechatMember();
			wechatUser.setCity(object.getString("city"));
			wechatUser.setCountry(object.getString("country"));
			wechatUser.setHeadimgurl(object.getString("headimgurl"));
			wechatUser.setLanguage(object.getString("language"));
			if(object.getString("nickname")!=null){
				wechatUser.setNickname(filterEmoji(object.getString("nickname")));
			}
			wechatUser.setOpenId(object.getString("openid"));
			wechatUser.setProvince(object.getString("province"));
			wechatUser.setSex(object.getString("sex"));
			//wechatUser.setSubscribe(object.getString("subscribe"));
			return wechatUser;
		}
		/**
		 * 获取关注者列表
		 * 第一个拉取的OPENID，不填为空字符串""默认从头开始拉取
		 * @author xiaoqian
		 * @param accessToken
		 * @param oponId
		 * @return
		 * @throws Exception
		 */
		
		public static WeChatUserList getWeChatUserList(String accessToken,String oponId)throws Exception{
			HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken+"&next_openid="+oponId);
			HttpResponse response = httpclient.execute(get);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			WeChatUserList weChatUserList=new WeChatUserList();
			JSONObject object=JSON.parseObject(jsonStr);
			JSONObject data=object.getJSONObject("data");
			weChatUserList.setTotal(Integer.parseInt(object.getString("total")));
			weChatUserList.setCount(Integer.parseInt(object.getString("count")));
			weChatUserList.setNext_openid(object.getString("next_openid"));
			weChatUserList.setOpenid(data.getJSONArray("openid").toArray());
			return weChatUserList;
		}
		
		/**
		 *获得微信分组的名称
		 * 第一个拉取的OPENID，不填为空字符串""默认从头开始拉取
		 * @author xiaoqian
		 * @param accessToken
		 * @param oponId
		 * @return
		 * @throws Exception
		 */
		
		public static List<Map<String, Object>> getWeChatGroupName(String accessToken)throws Exception{
			HttpGet get = HttpClientConnectionManager.getGetMethod("https://api.weixin.qq.com/cgi-bin/groups/get?access_token="+accessToken);
			HttpResponse response = httpclient.execute(get);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object=JSON.parseObject(jsonStr);
			Object[] data=object.getJSONArray("groups").toArray();
			List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
			for (int i = 0; i < data.length; i++) {
				JSONObject json=JSON.parseObject(data[i].toString());
				Map<String, Object> map =new HashMap<String, Object>();
				map.put("id", json.get("id").toString());
				map.put("name", json.get("name").toString());
				map.put("count", json.get("count").toString());
				
				list.add(map);
			}
			
			return list;
		}
		
		
		/**
		 * 发送客服消息
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
		
		public static String sendServiceMessage(String params, String accessToken) throws Exception {
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken);
			httpost.setEntity(new StringEntity(params, "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			return "返回状态："+object.toString()+"错误信息："+object.getString("errmsg");
		}
		
		
	
		
		/**
		 * @author Jakemanse
		 * @time 2014-5-9  下午12:14:13
		 * @function <p> 给会员发消息 </p>
		 * @param userId
		 * @param member
		 * @param title
		 * @param desc
		 * @param picUrl
		 * @param url
		 * @return
		 * @throws Exception
		 */
		
		public static String sendMsgToMember(Long userId,WechatMember member,String title,String desc,String picUrl,String url) throws Exception {
			
			WeChat weChat= weChatService.getWeChatByUserId(userId);
			String accessToken=WechatMenuUtils.getAccessToken(weChat.getAppId(), weChat.getAppSecret());
			
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken);
			String params = newsMessageParams(member.getWechatId(),title,desc,url,picUrl);
			httpost.setEntity(new StringEntity(params, "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			
			return "返回状态："+object.toString()+"错误信息："+object.getString("errmsg");
			
		}
		
		
		
		
		
		
		/**
		 * 生成文本客服消息json
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
		public static String textMessageParams(String openId,String content){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":\"").append(openId).append("\",");
			Message.append("\"msgtype\":\"text\",");
			Message.append("\"text\":");
			Message.append("{");
			Message.append(" \"content\":\"").append(content).append("\"");
			Message.append("}");
			Message.append("}");
			return Message.toString();
		}
		
		/**
		 * 生成图片客服消息json
		 * openId普通用户openid
		 * media_id发送的图片的媒体ID
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
		public static String imgMessageParams(String openId,String media_id){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":\"").append(openId).append("\",");
			Message.append("\"msgtype\":\"image\",");
			Message.append("\"image\":");
			Message.append("{");
			Message.append(" \"media_id\":\"").append(media_id).append("\"");
			Message.append("}");
			Message.append("}");
			return Message.toString();
		}
		
		
		/**
		 * 生成语音客服消息json
		 *  openId普通用户openid
		 * media_id发送的语音的媒体ID
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
		
		
		public static String voiceMessageParams(String openId,String media_id){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":\"").append(openId).append("\",");
			Message.append("\"msgtype\":\"voice\",");
			Message.append("\"voice\":");
			Message.append("{");
			Message.append(" \"media_id\":\"").append(media_id).append("\"");
			Message.append("}");
			Message.append("}");
			return Message.toString();
		}
		
		/**
		 * 生成视频客服消息json
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String videoMessageParams(String openId,String media_id,String title,String description){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":\"").append(openId).append("\",");
			Message.append("\"msgtype\":\"video\",");
			Message.append("\"video\":");
			Message.append("{");
			Message.append(" \"media_id\":\"").append(media_id).append("\",");
			Message.append(" \"title\":\"").append(title).append("\",");
			Message.append(" \"description\":\"").append(description).append("\"");
			Message.append("}");
			Message.append("}");
			return Message.toString();
		}
		
		
		/**
		 * 生成音乐客服消息json
		 * openId普通用户openid
		 * title音乐标题
		 * description音乐描述
		 * musicurl音乐链接
		 * hqmusicurl高品质音乐链接，wifi环境优先使用该链接播放音乐
		 * thumb_media_id缩略图的媒体ID
		 * 
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String musicMessageParams(String openId,String title,String description,String musicurl,String hqmusicurl,String thumb_media_id){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":\"").append(openId).append("\",");
			Message.append("\"msgtype\":\"music\",");
			Message.append("\"music\":");
			Message.append("{");
			Message.append(" \"title\":\"").append(title).append("\",");
			Message.append(" \"description\":\"").append(description).append("\",");
			Message.append(" \"musicurl\":\"").append(musicurl).append("\",");
			Message.append(" \"hqmusicurl\":\"").append(hqmusicurl).append("\",");
			Message.append(" \"thumb_media_id\":\"").append(thumb_media_id).append("\"");
			Message.append("}");
			Message.append("}");
			return Message.toString();
		}
		
		/**
		 * 生成单图文客服消息json
		 * openId普通用户openid
		 * title标题
		 * description描述
		 * 点击后跳转的链接
		 * picurl图文消息的图片链接，支持JPG、PNG格式，较好的效果为大图640*320，小图80*80
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String newsMessageParams(String openId,String title,String description,String url,String picurl){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":\"").append(openId).append("\",");
			Message.append("\"msgtype\":\"news\",");
			Message.append("\"news\":{");
			Message.append("\"articles\": [");
			Message.append("{");
			Message.append(" \"title\":\"").append(title).append("\",");
			Message.append(" \"description\":\"").append(description).append("\",");
			Message.append(" \"url\":\"").append(url).append("\",");
			Message.append(" \"picurl\":\"").append(picurl).append("\",");
			Message.append("}");
			Message.append("]");
			Message.append("}");
			Message.append("}");
			return Message.toString();
		}
		
		
		/**
		 * 生成单图文客服消息json
		 * openId普通用户openid
		 * title标题
		 * description描述
		 * 点击后跳转的链接
		 * picurl图文消息的图片链接，支持JPG、PNG格式，较好的效果为大图640*320，小图80*80
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String newsListMessageParams(String openId,List<ImageMessage> list){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":\"").append(openId).append("\",");
			Message.append("\"msgtype\":\"news\",");
			Message.append("\"news\":{");
			Message.append("\"articles\": [");
			for (int i = 0; i < list.size(); i++) {
				Message.append("{");
				Message.append(" \"title\":\"").append(list.get(i).getTitle()).append("\",");
				Message.append(" \"description\":\"").append(list.get(i).getDescription()).append("\",");
				Message.append(" \"url\":\"").append(list.get(i).getUrl()).append("\",");
				Message.append(" \"picurl\":\"").append(list.get(i).getPicUrl()).append("\"");
				Message.append("},");
			}
			Message.deleteCharAt(Message.lastIndexOf(","));
			Message.append("]");
			Message.append("}");
			Message.append("}");
			return Message.toString();
		}
		
		
		/**
		 * 创建二维码
		 *@author xiaoqian
		 * @param params
		 * @param accessToken
		 * @return
		 * @throws Exception
		 * 下午3:14:06
		 */
		public static JSONObject createQrCode(String params, String accessToken) throws Exception {
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken);
			httpost.setEntity(new StringEntity(params, "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			return object;
		}
		
		
		/**
		 * 创建临时二维码ticket
		 * expire_seconds最大不超过1800秒
		 * scene_id场景值ID，临时二维码时为32位非0整型，永久二维码时最大值为100000（目前参数只支持1--100000）
		*@author xiaoqian
		 * @param args
		 * @throws Exception
		 * 下午3:04:40
		 */
		public static String createTemporaryQrCodeParams(String expire_seconds, String scene_id) throws Exception {
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"expire_seconds\":").append(expire_seconds).append(",");
			Message.append("\"action_name\":\"QR_SCENE\",");
			Message.append("\"action_info\":{");
			Message.append("\"scene\": {");
			Message.append("\"scene_id\": ").append(scene_id);
			Message.append("}");
			Message.append("}");
			Message.append("}");
			return Message.toString();
		}
		
		/**
		 * 创建永久二维码ticket
		 *@author xiaoqian
		 * @param scene_id
		 * @return
		 * @throws Exception
		 * 2014-2-28下午4:04:26
		 */
		public static String createForeverQrCodeParams(String scene_id) throws Exception {
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"action_name\":\"QR_LIMIT_SCENE\",");
			Message.append("\"action_info\":{");
			Message.append("\"scene\": {");
			Message.append("\"scene_id\": ").append(scene_id);
			Message.append("}");
			Message.append("}");
			Message.append("}");
			return Message.toString();
		}
		
		
		
		
		
		/**
		 * 按组群发
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
		
		public static String massSendByGroup(String params, String accessToken) throws Exception {
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=" + accessToken);
			httpost.setEntity(new StringEntity(params, "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			System.out.println(object.toString());
			return object.getString("media_id");
		}
		
		/**
		 * 群发使用
		 * 上传图文的media_id
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
		
		public static String uploadNews(String params, String accessToken) throws Exception {
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=" + accessToken);
			httpost.setEntity(new StringEntity(params, "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			System.out.println(object.toString());
			return object.getString("media_id");
		}
		
		
		/**
		 * 媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）
		 *@author xiaoqian
		 * @param mediaType
		 * @param file
		 * @return
		 * @throws Exception
		 * 2015-8-26下午4:31:23
		 */
		public static String uploadMedia(String mediaType, File file,String token)
				throws Exception {
			 String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?type=" + mediaType+"&access_token="+token;
			 System.out.println(url);
			HttpPost httpost = new HttpPost(url);
			if (file != null) {
				 MultipartEntityBuilder builder = MultipartEntityBuilder.create();
				  FileBody fb = new FileBody(file);
	              builder.addPart("media", fb);
			      httpost.setEntity(builder.build());
			      httpost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
		    }
			CloseableHttpResponse response = httpclient.execute(httpost);
			 String responseContent = handleResponse(response);
			 JSONObject object = JSON.parseObject(responseContent);
			 if (httpost != null) {
					httpost.abort();
				}
			return object.getString("media_id");
		}

		public static String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
		    final StatusLine statusLine = response.getStatusLine();
		    final HttpEntity entity = response.getEntity();
		    if (statusLine.getStatusCode() >= 300) {
		      EntityUtils.consume(entity);
		      throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
		    }
		    return entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8);
		  }
		
		
		/**
		 * @author Jakemanse
		 * @time 2014-8-27  上午10:13:18
		 * @function <p> 群发  </p>
		 * @param openIds
		 * @return
		 */
		
		
		
		
		/**
		 * {
			   "touser":[
			    "OPENID1",
			    "OPENID2"
			   ],
			   "mpnews":{
			      "media_id":"123dsdajkasd231jhksad"
			   },
			    "msgtype":"mpnews"
			}
		 */
		public static String sendTextMessageToUsers(List<String> openIds,String content,String accessToken){
			String postUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+accessToken;
			
			if(openIds!=null && !openIds.isEmpty()){
				
			}
			
			//////
			String strOpenIds = "";
			StringBuffer jsonBuffer = new StringBuffer();
			jsonBuffer.append("{");
			jsonBuffer.append("\"user\":["+strOpenIds+"]").append(",");
			jsonBuffer.append("\"msgtype\": \"text\", ");
			jsonBuffer.append("\"text\": { \"content\": \""+content+"\"}");
			
			jsonBuffer.append("}");
			
			return null;
		}
		
		
		
		/**
		 * 上传群发图文
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String newsMessageParamsByMass(List<NewsMessageByMass> list){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"articles\":[");
			for (int i = 0; i < list.size(); i++) {
				
				Message.append("{");
				Message.append("\"thumb_media_id\":\""+list.get(i).getThumb_media_id()+"\",");
				if(list.get(i).getAuthor()!=null){
					Message.append("\"author\":\""+list.get(i).getAuthor()+"\",");
				}
				Message.append("\"title\":\""+list.get(i).getTitle()+"\",");
				if(list.get(i).getContent_source_url()!=null){
				Message.append("\"content_source_url\":\""+list.get(i).getContent_source_url()+"\",");
				}
				if(list.get(i).getDigest()!=null){
					Message.append("\"digest\":\""+list.get(i).getDigest()+"\",");
				}
				Message.append("\"content\":\""+list.get(i).getContent()+"\"");
				Message.append("}");
				if(i!=(list.size()-1)){
					Message.append(",");
				}
			}
			
			Message.append("]");
			Message.append("}");
			return Message.toString();
		}
		
		
		/**
		 * 按组群发图文
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String MassMessageParamsByNews(String group_id,String media_id){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"filter\":{");
			Message.append("\"group_id\":\""+group_id+"\"");
			Message.append("},");
			Message.append("\"mpnews\":{");
			Message.append("\"media_id\":\""+media_id+"\"");
			Message.append("},");
			Message.append("\"msgtype\":\"mpnews\"");
			
			Message.append("}");
			return Message.toString();
		}
		
		
		
		
		
		/**
		 * 按组群发文本
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String MassMessageParamsByText(String group_id,String content){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"filter\":{");
			Message.append("\"group_id\":\""+group_id+"\"");
			Message.append("},");
			Message.append("\"text\":{");
			Message.append("\"content\":\""+content+"\"");
			Message.append("},");
			Message.append("\"msgtype\":\"text\"");
			
			Message.append("}");
			return Message.toString();
		}
		
		/**
		 * 按组群发语音
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String MassMessageParamsByVoice(String group_id,String media_id){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"filter\":{");
			Message.append("\"group_id\":\""+group_id+"\"");
			Message.append("},");
			Message.append("\"voice\":{");
			Message.append("\"media_id\":\""+media_id+"\"");
			Message.append("},");
			Message.append("\"msgtype\":\"voice\"");
			
			Message.append("}");
			return Message.toString();
		}
		
		
		/**
		 * 按组群发图片
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String MassMessageParamsByImage(String group_id,String media_id){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"filter\":{");
			Message.append("\"group_id\":\""+group_id+"\"");
			Message.append("},");
			Message.append("\"image\":{");
			Message.append("\"media_id\":\""+media_id+"\"");
			Message.append("},");
			Message.append("\"msgtype\":\"image\"");
			
			Message.append("}");
			return Message.toString();
		}
		
		
		/**
		 * 按组群发视频
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String MassMessageParamsByMpvideo(String group_id,String media_id){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"filter\":{");
			Message.append("\"group_id\":\""+group_id+"\"");
			Message.append("},");
			Message.append("\"mpvideo\":{");
			Message.append("\"media_id\":\""+media_id+"\"");
			Message.append("},");
			Message.append("\"msgtype\":\"mpvideo\"");
			
			Message.append("}");
			return Message.toString();
		}
		
		
		
		
		/**
		 * 按openId群发
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
		
		public static String massSendByOpenId(String params, String accessToken) throws Exception {
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" + accessToken);
			httpost.setEntity(new StringEntity(params, "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			System.out.println(object.toString());
			return object.getString("media_id");
		}
		
		
		/**
		 * 按openId群发图文
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String MassMessageParamsByNews(List<String> list,String media_id){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":[");
			for (int i = 0; i < list.size(); i++) {
				Message.append("\""+list.get(i)+"\"");
				if( i!= (list.size()-1)){
					Message.append(",");
				}
			}
			Message.append("],");
			Message.append("\"mpnews\":{");
			Message.append("\"media_id\":\""+media_id+"\"");
			Message.append("},");
			Message.append("\"msgtype\":\"mpnews\"");
			
			Message.append("}");
			return Message.toString();
		}
		
		/**
		 * 按openId群发文本
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String MassMessageParamsByText(List<String> list,String content){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":[");
			for (int i = 0; i < list.size(); i++) {
				Message.append("\""+list.get(i)+"\"");
			}
			Message.append("],");
			Message.append("\"text\":{");
			Message.append("\"content\":\""+content+"\"");
			Message.append("},");
			Message.append("\"msgtype\":\"text\"");
			
			Message.append("}");
			return Message.toString();
		}
		
		
		/**
		 * 按openId群发语音
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String MassMessageParamsByVoice(List<String> list,String media_id){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":[");
			for (int i = 0; i < list.size(); i++) {
				Message.append("\""+list.get(i)+"\"");
			}
			Message.append("],");
			Message.append("\"voice\":{");
			Message.append("\"media_id\":\""+media_id+"\"");
			Message.append("},");
			Message.append("\"msgtype\":\"voice\"");
			
			Message.append("}");
			return Message.toString();
		}
		
		/**
		 * 按openId群发图片
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String MassMessageParamsByImage(List<String> list,String media_id){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":[");
			for (int i = 0; i < list.size(); i++) {
				Message.append("\""+list.get(i)+"\"");
			}
			Message.append("],");
			Message.append("\"image\":{");
			Message.append("\"media_id\":\""+media_id+"\"");
			Message.append("},");
			Message.append("\"msgtype\":\"image\"");
			
			Message.append("}");
			return Message.toString();
		}
		
		
		/**
		 * 按openId群发图片
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String MassMessageParamsByVideo(List<String> list,String media_id,String title,String description){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"touser\":[");
			for (int i = 0; i < list.size(); i++) {
				Message.append("\""+list.get(i)+"\"");
			}
			Message.append("],");
			Message.append("\"video\":{");
			Message.append("\"media_id\":\""+media_id+"\",");
			Message.append("\"title\":\""+media_id+"\",");
			Message.append("\"description\":\""+media_id+"\"");
			Message.append("},");
			Message.append("\"msgtype\":\"video\"");
			
			Message.append("}");
			return Message.toString();
		}
		
		/**
		 * 群发视频文件上传
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
		
		public static String uploadvideo(String params, String accessToken) throws Exception {
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://file.api.weixin.qq.com/cgi-bin/media/uploadvideo?access_token=" + accessToken);
			httpost.setEntity(new StringEntity(params, "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			System.out.println(object.toString());
			return object.getString("media_id");
		}
		
		
		/**
		 * 删除群发
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
		
		public static String massDelete(String msgid, String accessToken) throws Exception {
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com//cgi-bin/message/mass/delete?access_token=" + accessToken);
			StringBuffer params = new StringBuffer();
			params.append("{");
			params.append("\"msgid\":\""+msgid+"\",");
			params.append("}");
			
			httpost.setEntity(new StringEntity(params.toString(), "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			System.out.println(object.toString());
			return object.getString("media_id");
		}
		
		
		/**
		 * 按openId群发图片
		 * @author xiaoqian
		 * @param args
		 * @throws Exception
		 */
				
		public static String uploadVideoParams(String media_id,String title,String description){
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"media_id\":\""+media_id+"\",");
			Message.append("\"title\":\""+media_id+"\",");
			Message.append("\"description\":\""+media_id+"\"");
			Message.append("}");
			return Message.toString();
		}
		
		
		/**
		 * 创建分组
		 *@author xiaoqian
		 * @param params
		 * @param accessToken
		 * @return
		 * @throws Exception
		 * 2014-5-14上午10:03:45
		 */
		public static String createGroup(String groupName, String accessToken) throws Exception {
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"group\":{\"name\":\""+groupName+"\"},");
			Message.append("}");
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/groups/create?access_token=" + accessToken);
			httpost.setEntity(new StringEntity(Message.toString(), "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			JSONObject object1 = JSON.parseObject(object.getString("group"));
			System.out.println(object.toString());
			return object1.getString("id");
		}
		
		
		/**
		 * 移动分组
		 *@author xiaoqian
		 * @param groupName
		 * @param accessToken
		 * @return
		 * @throws Exception
		 * 2014-5-14上午10:14:25
		 */
		public static String addMemberByGroup(String openId,String groupId, String accessToken) throws Exception {
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"openid\":\""+openId+"\",\"to_groupid\":"+groupId);
			Message.append("}");
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=" + accessToken);
			httpost.setEntity(new StringEntity(Message.toString(), "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			System.out.println(object.toString());
			return object.getString("errmsg");
		}
		
		
		/**
		 * 修改分组名称
		 *@author xiaoqian
		 * @param openId
		 * @param groupId
		 * @param accessToken
		 * @return
		 * @throws Exception
		 * 2014-5-14上午10:39:54
		 */
		public static String updateGroupName(String groupName,String groupId, String accessToken) throws Exception {
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"group\":{\"id\":\""+groupId+"\",\"name\":\""+groupName+"\"},");
			Message.append("}");
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/groups/update?access_token=" + accessToken);
			httpost.setEntity(new StringEntity(Message.toString(), "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			System.out.println(object.toString());
			return object.getString("errmsg");
		}
		
		
		public static String getGroupByOpenId(String groupId, String accessToken) throws Exception {
			StringBuffer Message = new StringBuffer();
			Message.append("{");
			Message.append("\"openid\":\""+groupId+"\"");
			Message.append("}");
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=" + accessToken);
			httpost.setEntity(new StringEntity(Message.toString(), "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			System.out.println(object.toString());
			return object.getString("groupid");
		}
		
		/**
		 * emoji  处理
		 *@author xiaoqian
		 * @param codePoint
		 * @return
		 * 2015-1-9下午3:19:12
		 */
		private static boolean isNotEmojiCharacter(char codePoint)  
		{  
		    return (codePoint == 0x0) ||  
		        (codePoint == 0x9) ||  
		        (codePoint == 0xA) ||  
		        (codePoint == 0xD) ||  
		        ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||  
		        ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||  
		        ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));  
		}  
		  
		/** 
		 * 过滤emoji 或者 其他非文字类型的字符 
		 * @param source 
		 * @return 
		 */  
		public static String filterEmoji(String source)  
		{  
		    int len = source.length();  
		    StringBuilder buf = new StringBuilder(len);  
		    for (int i = 0; i < len; i++)  
		    {  
		        char codePoint = source.charAt(i);  
		        if (isNotEmojiCharacter(codePoint))  
		        {  
		            buf.append(codePoint);  
		        }  
		    }  
		    return buf.toString();  
		}  
	    
		
		/**
		 * 从质询服务器获得笑话
		 *@author xiaoqian
		 * @return
		 * 2015-4-9下午2:01:44
		 */
		public static List<Witticism> getWitticism() {

			String url = "http://www.hdzhx.com/zxims/f/wechat/API/witticismJson";

			try {
				HttpGet get = new HttpGet(url.replace(" ", ""));
				HttpResponse response = httpclient.execute(get);
				String jsonStr = EntityUtils
						.toString(response.getEntity(), "utf-8");
				List<Witticism> witticismList = new ArrayList<Witticism>();

				//获得json列表
				JSONArray jsonArray = JSON.parseArray(jsonStr);
				
				for (int j = 0; j < jsonArray.size(); j++) {
					JSONObject json =  jsonArray.getJSONObject(j);
					Witticism witticism = new  Witticism();
					witticism.setId(Long.parseLong(json.get("id")+""));
					witticism.setTitle(json.get("title")+"");
					witticism.setPicUrl(json.get("picUrl")+"");
					witticismList.add(witticism);
					
				}
				
				return witticismList;

			} catch (Exception e) {
				e.printStackTrace();
			}

			return null;

		}
		
		/**
		 * 回复消息
		 * @param userId
		 * @param member
		 * @param content
		 * @return
		 * @throws Exception
		 */
		public static  String sendTextMessageToMember(Long userId,WechatMember member,String params) throws Exception{
			WeChat weChat=  weChatService.getWeChatByUserId(userId);
			String accessToken = TokenUtils.getAPIToken(weChat);
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken);
//			String params = textMessageParams(member.getWechatId(),content);
			httpost.setEntity(new StringEntity(params, "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			response.getEntity().getContent().close();
			
			System.out.println("返回状态："+object.toString()+"错误信息："+object.getString("errmsg"));
			
			return "返回状态："+object.toString()+"错误信息："+object.getString("errmsg");
		}
		
		/**
		 * 回复消息
		 * @param userId
		 * @param member
		 * @param content
		 * @return
		 * @throws Exception
		 */
		public static  String sendTextMessageToMember1(Long userId,WechatMember member,String content) throws Exception{
			WeChat weChat=  weChatService.getWeChatByUserId(userId);
			String accessToken = TokenUtils.getAPIToken(weChat);
			HttpPost httpost = HttpClientConnectionManager.getPostMethod("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken);
			String params = textMessageParams(member.getWechatId(),content);
			httpost.setEntity(new StringEntity(params, "UTF-8"));//params  为post请求的
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			JSONObject object = JSON.parseObject(jsonStr);
			response.getEntity().getContent().close();
			
			System.out.println("返回状态："+object.toString()+"错误信息："+object.getString("errmsg"));
			
			return "返回状态："+object.toString()+"错误信息："+object.getString("errmsg");
		}
	 
		
		
		public static void main(String[] args) throws Exception {
			
			//String accessToken=WechatMenuUtils.getAccessToken("wxa089048968118e44", "8205df06d6b72e95e0c8e2bacce6c2a9");
			String accessToken="gbTpiKoJp5IUIAEp6sTzkepgqZ_KbSuBUJwwygKhSvKPJzxjRu63vGSpmT8VRZH0wPoz0JyijqsymDdQFkpEVWCuzg9kqn545QC2bUE2opN6ftOnjzEFUvmy8s2qSEZsITZeAFARCI";
			String params = WechatInterfaceUtils.newsMessageParams("o0TmhuM3k0GYP3dVKscFnlHTkHK8","支付","灌灌灌灌哈哈哈","http://www.baidu.com","");
			System.out.println(params);
			WechatInterfaceUtils.sendServiceMessage(params,accessToken);
//			List<NewsMessageByMass> list=new ArrayList<NewsMessageByMass>();
//			
//			NewsMessageByMass newsMessageByMass1=new NewsMessageByMass();
//			newsMessageByMass1.setAuthor("tom");
//			newsMessageByMass1.setContent("test1");
//			newsMessageByMass1.setContent_source_url("www.baidu.com");
//			newsMessageByMass1.setDigest("大美女");
//			newsMessageByMass1.setThumb_media_id("DMUdt1LIDrdbrHpY-98EEgFfpfDNFsfHEt7Ym1rhqx4PwxKxGLLVbtK7BjsIhopT");
//			newsMessageByMass1.setTitle("标题大美女");
//			
//			NewsMessageByMass newsMessageByMass2=new NewsMessageByMass();
//			
//			newsMessageByMass2.setContent_source_url("http://mp.weixin.qq.com/s?__biz=MjM5NjYyOTM4Mg==&mid=200352272&idx=1&sn=1934975fbaaaa41078885af902c8e0db#rd");
//			newsMessageByMass2.setContent("test1");
//			newsMessageByMass2.setDigest("比特堡与卡而汽车开展合作，微会员只要在比特堡平台签到，即可获得由卡而汽车服务会所送出的免费洗车卡一张！该卡可免费洗车一次！");
//			newsMessageByMass2.setThumb_media_id("9mm7dfev9imjHdVvwTXwU2rGtWgtzoimIS0Km5noyxYyFzWjvJptlCLERqkUA7_d");
//			newsMessageByMass2.setTitle("价值50元洗车卡免费送啦！先到先得！");
////			
////			list.add(newsMessageByMass1);
//			list.add(newsMessageByMass2);
//			String params=newsMessageParamsByMass(list);
//			System.out.println(params);
			
//			System.out.println(createGroup("test", accessToken));
			
//			System.out.println(updateGroupName("group15", "102", accessToken));
//			System.out.println(addMemberByGroup("oYH21jneaJN--ytbik_vDC0OwC3Q", "102", accessToken));
//			System.out.println(getWeChatGroupName(accessToken).toString());
			
			
//			NewsMessageByMass newsMessageByMass2=new NewsMessageByMass();
//			newsMessageByMass2.setContent("<div><div><p><span>比特堡与卡而汽车开展合作，微会员只要在比特堡平台签到，即可获得由</span><span><strong>卡而汽车服务会所</strong></span><span>送出的</span><span><strong>免费洗车卡一张</strong><strong>！</strong></span><span>该卡可免费洗车一次！</span></p><p>&nbsp;</p><p><span>中奖的微会员需关注【邯郸卡而汽车服务】并注册成为会员，在<span>卡而汽车微信公众平台回复【洗车卡】领取奖品</span>，到卡而汽车门店核销使用，请勿在比特堡平台核销！</span></p><p>&nbsp;</p><p><strong><span>微信搜索公众号：</span></strong><span><strong>【hdke111】进行注册</strong></span></p><p>&nbsp;</p><p><span>注：微会员可使用一次，领取后请在5月31日前核销使用，过期作废！</span></p><p>&nbsp;</p><p><strong><span>客服电话：</span></strong><span>0310-3092666</span></p><p><span>0310-3090168</span></p><p><strong><span>技术支持：</span></strong><span>0310-7056607</span></p><p>&nbsp;</p><p><strong><span>卡而汽车服务会所地址：</span></strong><span>邯郸市东环路与联防路交叉口北行２００米路东（比亚迪４Ｓ店相邻）</span></p><p>&nbsp;</p><p><span><strong>卡而汽车服务会所简介</strong></span></p><p>&nbsp;</p><p><span>卡而汽车服务会所创建于2007年，历经五年现已成为市内颇具实力的汽车服务连锁企业，是集环保洗车、汽车美容、装饰、维修保养、烤漆、车饰、车险、汽车俱乐部于一体的综合性汽车服务会所。</span></p><p>&nbsp;</p><p><span>卡而始终坚持诚信经营、顾客至上。通过品质、技术和服务的三大优势，使我们得到了客户充分的认可。固定会员现已超过1000余名，服务项目多达80余种，如今的卡而正以专业的技术、贴心的服务壮大自己。以服务区区域覆盖全国为最终发展目标，努力成为消费者身边的汽车服务专家。</span></p><p>&nbsp;</p><p ><span>卡而始终坚持诚信经营、顾客至上。通过品质、技术和服务的三大优势，使我们得到了客户充分的认可。固定会员现已超过1000余名，服务项目多达80余种， 如今的卡而正以专业的技术、贴心的服务壮大自己。以服务区区域覆盖全国为最终发展目标，努力成为消费者身边的汽车服务专家。</span></p></div></div><br />");
//			newsMessageByMass2.setContent_source_url("http://mp.weixin.qq.com/s?__biz=MjM5NjYyOTM4Mg==&mid=200352272&idx=1&sn=1934975fbaaaa41078885af902c8e0db#rd");
//			newsMessageByMass2.setDigest("比特堡与卡而汽车开展合作，微会员只要在比特堡平台签到，即可获得由卡而汽车服务会所送出的免费洗车卡一张！该卡可免费洗车一次！");
//			newsMessageByMass2.setThumb_media_id("bBljkjcIpOdyoSE9htBhsSWQpLgmZrZlMBDo3gcpBYkFPHb1cnO1jC5p9fQmo4A-");
//			newsMessageByMass2.setTitle("价值50元洗车卡免费送啦！先到先得！");
//			list.add(newsMessageByMass2);
//			String params=WechatInterfaceUtils.newsMessageParamsByMass(list);
//			System.out.println(WechatInterfaceUtils.uploadNews(params, accessToken));
//			System.out.println(params);
//			
//			String params=MassMessageParamsByNews("119", "5ZvXyRdz-Lb0MLk8VprQN_somekDmwS7wJJPADMMWUkxLm2P7L1aqjNZMwArCcG5");
			//String params=MassMessageParamsByNews("126", "qEREY8XAJ5as6Zkr3NfxWLUQP04_nASxBe9LlY3SGmTjuiuxPDFj8NmDEv5CWk7a");
//			massSendByGroup(params, accessToken);
			
			
			
			
//			System.out.println(uploadNews(params, accessToken));
			
			
			
//			String test = "{\"group\":{\"id\":102,\"name\":\"group1\"}}"; 
//			
//			 JSONObject jsonObject= JSON.parseObject(test);
//			 ;
//			 System.out.println(jsonObject.getString("group"));
//			 JSONObject jsonObjec1= JSON.parseObject(jsonObject.getString("group"));
//			 System.out.println(jsonObjec1.getString("id"));
//			 System.out.println(getGroupByOpenId("ohqnZjsFQ8ERfgrWPNPC0w-PpO8I", accessToken));
//			 List<Map<String, Object>> list= daoHelper.getMember();
//			 
//			 System.out.println(list.get(1).get(""));
//			
//			System.out.println(sendServiceMessage(textMessageParams("ohqnZjopaS7ctA7DtDwxgfdkaSIQ", "aaa"), accessToken));
			
//			System.out.println(526%526);
		}
		
		
		@Override
		public void setApplicationContext(ApplicationContext applicationContext)
				throws BeansException {
			weChatService  = (WeChatService) applicationContext.getBean("weChatService");
			daoHelper  = (WechatDaoHelper) applicationContext.getBean("wechatDaoHelper");
			
		}
		
		
		
}
